import router, { constantRoutes } from '@/lib/router/index';
import store from '@/extend/store';
import { beforeRouter, afterRouter } from '@/lib/router/permission';
import asyncRoutes from '@/lib/router/module/index';
// import detail from './module/detail';
import { api_GET_MessageGetUnReadMessagesTotal } from '@/extend/api/swaggerApi/chat.js';
import { api_GET_MallStoreCurrent } from '@/extend/api/shoppingmallswaggerApi/app.js';
import { api_GET_UsersPemissionOrganizationUnits } from '@/extend/api/swaggerApi/identity.js';
import { Message } from 'element-ui';
import { judgeToLogout } from '@/lib/oidc_fun';
import { clearOut } from '@/lib/store/modules/user';
import { setToken, getUserToken } from '@/lib/auth';
import Cache from '@/lib/cache';

// 动态添加路由
export function addRouters (routerList, odlRouterList) {
  router.addRoutes(routerList);
  const beforRouterList = odlRouterList || (store.permission.routerList && store.permission.routerList.length > 0) || constantRoutes;
  store.dispatch('permission/addRoutes', [...beforRouterList, ...routerList]);
}

const whiteList = ['/login', '/forgetPassword', '/register', '/recgamedetail']; // no redirect whitelist
// 路由跳转检测
router.beforeEach((to, from, next) => {
  if (to.query.token) {
    if (!store.state.app.isgetBadge) {
      setToken(to.query.token);
    }
  }
  beforeRouter(to, from, next, store, router, [...asyncRoutes], whiteList, initToDo);
  next();
});

router.afterEach(() => {
  afterRouter();
});

// 初始化只执行一次的操作
async function initToDo (to, next) {
  // 获取当前用户注册类型（根据用户类型跳转至对应页面）
  // TODO 获取徽标数据
  if (store.state.user.info.permissions.includes('Chat.Messaging.Read')) {
    api_GET_MessageGetUnReadMessagesTotal().then(res => {
      store.dispatch('permission/setRouterBadge', { Inbox: res });
    });
  }
  await getUserToken();

  await api_GET_UsersPemissionOrganizationUnits()
    .then(
      res => {
        // 根据接口返回数据获取OUID，
        // 如果localStorage中存在OUID，那么校验此ID是否存在于res列表中。
        // 如果存在，则使用该ID
        // 如果不存在，则使用res中的第一个，并更新localStorage中存在OUID。
        // 程序继续执行
        const _firstOuid = res[0].id;
        const _localOUid = Cache.get('current_ou');
        if (_localOUid) {
          const _findOU = res.find(item => item.id === _localOUid);
          const _ouid = _findOU ? _findOU.id : _firstOuid;
          store.dispatch('user/setCurrentOUID', _ouid);
        } else {
          store.dispatch('user/setCurrentOUID', _firstOuid);
        }
      }
    )
    .catch(
      error => {
        // 接口获取失败，程序依旧执行。此时OUID可能不存在或有问题。
        console.log('ERROR: src/extend/router/platform/index api_GET_UsersPemissionOrganizationUnits', error);
      }
    );

  if (!store.state.user.info || store.state.user.info.permissions.length <= 0) {
    Message.error('该账号无任何权限，请联系管理员添加权限！');
    const tenantId =
      store.state.user.info && store.state.user.info.tenantId
        ? store.state.user.info.tenantId
        : to.query.tenantid ? to.query.tenantid : '';
    clearOut();
    setTimeout(() => {
      judgeToLogout(window.location.origin + window.location.pathname + '#/?tenantid=' + tenantId);
      // mgr.signinRedirect({
      //   state: window.btoa(window.location.href),
      //   acr_values: router.currentRoute.query.tenantid ? window.btoa(router.currentRoute.query.tenantid) : ''
      // }); // 跳转登录
    }, 1000);
  }

  // 如果用户被禁用，则 currentOrganizationUnit 与 currentOrganizationUnitId 为 null
  const _currentOrganizationUnit = store.state.user.info.currentOrganizationUnit;
  const _currentOrganizationUnitId = store.state.user.info.currentOrganizationUnitId;
  if (!_currentOrganizationUnit && !_currentOrganizationUnitId) {
    next({ path: '/404', replace: true });
    return true;
  }
  // 获取路由信息
  const routers = await store.dispatch('user/getRouter');
  console.log(routers);
  // 根据权限获取当前路由表
  // extendRouterList = extendRouterList ? extendRouterList : [];
  const tenantId = store.state.user.info && store.state.user.info.tenantId
    ? store.state.user.info.tenantId
    : to.query.tenantid ? to.query.tenantid : '';
  const accessRoutes = await store.dispatch('permission/generateRoutes', { routers, extendRouterList: [...asyncRoutes], tenantId });
  // 添加动态路由
  console.log(accessRoutes);
  console.log(router.options.routes);
  router.options.routes = [...router.options.routes, ...accessRoutes];
  console.log(router.options.routes);
  await router.addRoutes(accessRoutes);
  console.log(to);
  // TODO 获取店铺数据
  if (store.state.user.info.permissions.includes('Mall.Store')) {
    await api_GET_MallStoreCurrent({ IncludeStatus: true }).then(res => {
      console.log('shopings-----------', res);
      if (res) {
        store.dispatch('permission/setRouterDisable', { Mall: false });
      }
    }, error => {
      const _msg = error.error.message || error.message;
      Message({ type: 'error', message: _msg });
    });
  }
  let _to = to;
  store.dispatch('app/setIsGetBadge', true);
  if (!to.params.tenantId) {
    if (to.path === '/') {
      _to = { name: 'baserouter', params: { tenantId: 't__' + tenantId }};
    } else {
      console.log(2);
      if (!/^\/t__/.test(to.path)) {
        next({ ..._to, ...{ path: '/t__' + tenantId + to.path }, replace: true });
      }
      _to.params.tenantId = '/t__' + tenantId;
      console.log(3);
    }
    next({ ..._to, replace: true });
  }
  if (!/^\/t__/.test(to.path)) {
    next({ ..._to, ...{ path: '/t__' + tenantId + to.path }, replace: true });
  }
  return true;
}

export default router;
